<?php
namespace Manager\Controller;

use Think\Controller;

class CategoryController extends Controller {

	// 添加分类
	// 不需要提供参数、post提交就处理添加的逻辑、否则显示添加表单
	public function addCategory()
	{
		$m = D("Category");
		if(IS_POST)
		{
			$data 			= $m->create();
			$data["sort"]	= (int)($data["sort"]);
			$data["active"]	= (int)($data["active"]);
			if($m->add($data))
			{
				$this->success("添加分类成功",U("Category/addCategory"));
			}
			else
			{
				$this->error("添加分类失败",U("Category/addCategory"));
			}
			return ;
		}
		else
		{
			$categorys = $m->getCategory();
			$this->assign("categorys",$categorys);
		}
		$this->display();
	}

	// 用于分类名判重 ajax
	// 在添加分类时使用name判重
	public function getCategoryByName()
	{
		$name 	= I("get.name");
		$m = D("Category");

		if($m->getCategoryByName($name))
		{
			$res["code"]	= 0;
			$res["message"]	= "分类名重复";
		}
		else
		{
			$res["code"]	= 1;
			$res["message"]	= "分类名可用";
		}
		return $this->ajaxReturn($res);
	}

	// 分类列表
	public function categoryList()
	{
		$m = D("Category");
		$id = I("get.parentid",0,"int");
		$categoryList 	= $m->getCategoryList($id);
		$link 			= U("Category/categoryUpdate");
		$delete 		= U("Category/deleteCategory");

		$this->assign("delete",$delete);
		$this->assign("link",$link);
		$this->assign("categoryList",$categoryList);
		$this->display();
	}

	// 某个编号的分类信息、以及所有分类的编号和名称信息
	public function categoryUpdate()
	{
		$m = D("Category");
		if(IS_POST)
		{
			$data = $m->create();
			if($m->save($data))
			{
				$this->success("修改成功",U("Category/categoryList"));
			}
			else
			{
				$this->error("修改失败",U("Category/categoryList"));
			}
			return ;
		}		
		$id = I("get.id");

		$category = $m->getCategoryById($id);
		$this->assign("category",$category);

		// 分类排除修改的分类
		$categorys = $m->getCategoryNoId($id);
		$this->assign("categorys",$categorys);
		$this->display();
	}

	// 分类信息修改中间页面
	public function categoryUpdateCenter()
	{
		$this->display();
	}

	// 通过id获得分类、ajax
	public function getCategoryById()
	{
		$id = I("get.id");
		$m = D("Category");

		if($m->getCategoryById($id))
		{
			$res["code"]	= 1;
			$res["message"]	= "分类可操作";
		}
		else
		{
			$res["code"]	= 0;
			$res["message"]	= "分类不存在";
		}
		return $this->ajaxReturn($res);
	}

	// 下架分类
	public function downCategory()
	{
		$id = I("get.id",null,"int");

		if(!empty($id))
		{
			$m = D("Category");
			if($m->downCategory($id))
			{
				$this->success("下架成功",U("Category/categoryList"));
			}
			else
			{
				$this->success("下架失败",U("Category/categoryList"));
			}
			return ;
		}
		$this->display();
	}

	public function deleteCategory()
	{
		$id = I("get.id");
		echo $id;
	}
}